package com.example.components.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: lu
 * Date: 2022/1/26
 * Time: 16:37
 * Version: 1.0
 * Modified By:
 * Description:
 */
public class HttpProxyPost {

    private static Logger logger = LoggerFactory.getLogger(HttpProxyPost.class);
    private static PropertiesUtils config = PropertiesUtils.getInstance();

    private static CloseableHttpClient client = null;

    public static String requestWithPost(String postUrl, JSONObject reqJson, Boolean https, Boolean proxy) {
        try {
            client = SSLClient.getHttpsClient(https);
        } catch (Exception e) {
            logger.error("获取httpCliet失败");
        }
        HttpPost post = new HttpPost(postUrl);
        if (proxy) {
            String proxyIP = config.getProperty("proxyIP");
            int proxyPort = Integer.parseInt(config.getProperty("proxyPort"));
            logger.info("使用代理发送请求：{}:{}", proxyIP, proxyPort);
            HttpHost proxyHost = new HttpHost(proxyIP, proxyPort);
            RequestConfig reqConfig = RequestConfig.custom().setProxy(proxyHost).build();
            post.setConfig(reqConfig);
        }
        StringEntity params = null;
        String rspStr = "";
        try {
            params = new StringEntity(reqJson.toString(), "utf-8");
            params.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            params.setChunked(true);
            post.addHeader("content-type", "application/json");
            post.setEntity(params);
            HttpResponse rsp = client.execute(post);
            HttpEntity entity = rsp.getEntity();
            String rspString = EntityUtils.toString(entity, "utf-8");
            JSONObject rspJson = JSONObject.parseObject(rspString);
            logger.info("请求返回报文：{}", rspJson);
            rspStr = rspJson.toString();
        } catch (Exception e) {
            logger.info("外调异常：：{}", e.getMessage());
        } finally {
            client.getConnectionManager().shutdown();
        }
        return rspStr;
    }
}
